<template>
  <div class="addvideo">
    <h1 v-if="this.$route.query.id == undefined">添加视频</h1>
    <h1 v-else>编辑视频</h1>
    <el-form label-width="100px" :model="formline" :rules="rules" ref="formline">
      <el-form-item label="时间:" prop="timenode">
        <div class="block">
          <el-input v-model="formline.timenode" placeholder="请输入内容" style="width:30%"></el-input>
        </div>
      </el-form-item>
      <el-form-item label="阶段:" prop="introduction">
        <el-input v-model="formline.introduction" placeholder="请输入内容" style="width:30%"></el-input>
      </el-form-item>
      <el-form-item label="视频地址:" prop="liveurl">
        <el-input v-model="formline.liveurl" placeholder="请输入内容" style="width:30%"></el-input>
      </el-form-item>
     <el-form-item label="视频封面:" label-width="100px" prop="manimagesrc">
        <template slot-scope="scope">
          <form class="banner_loade" enctype="multipart/form-data">
            <el-button class="upload" type="primary ">
              上传
              <input class="file" type="file" name="file" @change="uploadImg($event)" />
            </el-button>
            <div class="loade_img">
              <img class="img_auto" :src="imgs" alt />
            </div>
          </form>
        </template>
      </el-form-item>
    </el-form>
    <el-row style="text-align: center; margin-top:20px;">
      <el-button type="button" @click="cancel">取消</el-button>
      <el-button type="primary" @click="saveInfo">保存</el-button>
    </el-row>
  </div>
</template>

<script>
  import E from "wangeditor";
  import $ from "jquery";
  import Qiniu from "../../../static/js/qiniu";
  export default {
    data() {
      return {
        editorContent: "",
        formline: {
          introduction: "",
          liveurl: "",
          timenode: "",
          manimagesrc: ''
        },
        imgs:'',
        rules: {
          introduction: [{
            required: true,
            message: '请填写简介信息',
            trigger: 'blur'
          }],
          liveurl: [{
            required: true,
            message: '请填写直播链接',
            trigger: 'blur'
          }],
          timenode: [{
            required: true,
            message: '请输入时间',
            trigger: 'blur'
          }],

        }

      };
    },
    mounted() {
      setTimeout(() => {
        this.wangeditor();
      }, 1000)
      if (this.$route.query.id != undefined) {
        this.api.get("/api/findlive?id=" + this.$route.query.id).then(res => {
          console.log(res, "你好呀");
          if (res.code == 200) {
            this.editorContent = res.data.timenodeDetail;
            this.formline.introduction = res.data.introduction;
            this.formline.liveurl = res.data.liveurl;
            this.formline.timenode = res.data.timenode;
            this.imgs=res.data.fmian;
          }
        });
      }
    },
    methods: {
      uploadImg(e, index) {
        let file = e.target.files[0];
        let param = new FormData();
        param.append("files", file, file.name);
        console.log(param);
        let config = {
          headers: {
            "Content-Type": "multipart/form-data"
          }
        };
        this.api.post("/api/imgs", param, config).then(res => {
          console.log(res.data[0])
          this.imgs = res.data[0]
        });
      },
      cancel() {
        this.$router.go(-1)
      },
      //富文本实例
      wangeditor() {
        var editor = new E("#editorElem");
        editor.customConfig.onchange = html => {
          this.editorContent = html;
        };
        editor.customConfig.qiniu = true;
        editor.create();
        console.log(this.editorContent, "大哥呀  别打脸");
        editor.txt.html(this.editorContent);
        this.uploaderInit(editor);
      },
      // 提交数据
      saveInfo() {
        let me = this;
        this.$refs.formline.validate((valid) => {
          if (valid) {
            let video = {
              introduction: this.formline.introduction,
              liveurl: this.formline.liveurl,
              timenode: this.formline.timenode,
              timenode_detail: this.editorContent,
              userid: this.$route.query.userid,
              fmian:this.imgs
            };
            if (this.$route.query.id != undefined) {
              this.$set(video, 'id', this.$route.query.id);
              this.api.post("/api/edit", video).then(res => {
                if (res.code == 200) {
                  this.$message({
                    type: 'success',
                    message: '保存成功!'
                  })
                  setTimeout(() => {
                    me.$router.go(-1);
                  }, 2000);
                }
              });
            } else {
              console.log(this.$route.query.userid, 'qiqiqiqi')
              this.api.post("/api/add", video).then((res) => {
                if (res.code == 200) {
                  this.editorContent = res.data.timenodeDetail;
                  this.introduction = res.data.introduction;
                  this.liveurl = res.data.liveurl;
                  this.timenode = res.data.timenode;
                  this.imgs=res.data.fmian
                  this.$message({
                    type: 'success',
                    message: '保存成功!'
                  })
                  setTimeout(() => {
                    me.$router.go(-1);
                  }, 2000);
                }
              })
            }
          }
        })
      },
      // 富文本
      uploaderInit(editor) {
        var that = this;
        var btnId = editor.imgMenuId;
        var containerId = editor.toolbarElemId;
        var textElemId = editor.textElemId;
        that.api.post("/api/uptoken", {}).then(res => {
          var uploader = new Qiniu().uploader({
            runtimes: "html5,flash,html4", //上传模式,依次退化
            browse_button: btnId, //上传选择的点选按钮，**必需**
            uptoken: res.data,
            unique_names: true,
            save_key: true,
            domain: "http://vrqn.liuliangin.com/", //bucket 域名，下载资源时用到，**必需**
            container: containerId, //上传区域DOM ID，默认是browser_button的父元素，
            max_file_size: "100mb", //最大文件体积限制
            filters: {
              mime_types: [
                //只允许上传图片文件 （注意，extensions中，逗号后面不要加空格）
                {
                  title: "图片文件",
                  extensions: "jpg,gif,png,bmp"
                }
              ]
            },
            max_retries: 3, //上传失败最大重试次数
            dragdrop: true, //开启可拖曳上传
            drop_element: textElemId, //拖曳上传区域元素的ID，拖曳文件或文件夹后可触发上传
            chunk_size: "4mb", //分块上传时，每片的体积
            auto_start: true, //选择文件后自动上传，若关闭需要自己绑定事件触发上传
            init: {
              FilesAdded: function(up, files) {
                plupload.each(files, function(file) {
                  // 文件添加进队列后,处理相关的事情
                  that.printLog("on FilesAdded");
                });
              },
              BeforeUpload: function(up, file) {
                // 每个文件上传前,处理相关的事情
                that.printLog("on BeforeUpload");
              },
              UploadProgress: function(up, file) {
                // 显示进度
                that.printLog("进度 " + file.percent);
              },
              FileUploaded: function(up, file, info) {
                // 每个文件上传成功后,处理相关的事情
                // 其中 info 是文件上传成功后，服务端返回的json，形式如
                // {
                //    "hash": "Fh8xVqod2MQ1mocfI4S4KpRL6D98",
                //    "key": "gogopher.jpg"
                //  }
                that.printLog(info);
                // 参考http://developer.qiniu.com/docs/v6/api/overview/up/response/simple-response.html
                var domain = up.getOption("domain");
                var res = $.parseJSON(info.response);
                var sourceLink = domain + res.key; //获取上传成功后的文件的Url
                that.printLog(sourceLink);
                // 插入图片到editor
                editor.cmd.do(
                  "insertHtml",
                  '<img src="' + sourceLink + '" style="max-width:100%;"/>'
                );
              },
              Error: function(up, err, errTip) {
                //上传出错时,处理相关的事情
                that.printLog("on Error");
              },
              UploadComplete: function() {
                //队列文件处理完毕后,处理相关的事情
                that.printLog("on UploadComplete");
              }
            }
            //upload的括号
          });
        });
      },
      printLog(title, info) {
        console.log(title, "1");
        console.log(info, "2");
        window.console && console.log(title, info);
      }
      // 富文本结束
    }
  };
</script>

<style scoped>
  .file {
    position: absolute;
    left: 0;
    top: 0;
    width: 100%;
    height: 35px;
    line-height: 35px;
    text-align: center;
    opacity: 0;
  }

  .el-button {
    width: 100px;
  }

  .banner_loade {
    height: 100px;
  }

  .loade_img {
    background: url("./../../../static/img/push.jpg") no-repeat;
    position: absolute;
    top: 0;
    background-size: 80px 80px;
    width: 80px;
    height: 80px;
    left: 130px;
  }


  .img_auto {
   max-width: 100%;
   width: 100%;
   max-height: 100%;
   height: 100%;
   object-fit: cover;
  }

  .upload {
    position: relative;
    width: 120px;
    height: 35px;
  }
</style>
